package com.ec.fb.aop;

import com.ec.common.constant.CacheConstants;
import com.ec.common.utils.CacheClient;
import com.ec.fb.domain.po.Feedback;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Set;

@Slf4j
@Aspect
@Component
@RequiredArgsConstructor
public class CacheEvictionAspect {
    private final CacheClient cacheClient;
    private final StringRedisTemplate stringRedisTemplate;

    @AfterReturning("execution(* com.ec.fb.mapper.FeedbackMapper.insert(..)) || " +
                    "execution(* com.ec.fb.mapper.FeedbackMapper.updateById(..))")
    public void evictFeedbackCache(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        Long userId = null;
        if (args[0] instanceof Feedback) {
            Feedback feedback = (Feedback) args[0];
            userId = feedback.getUserId();
        }
        if (userId != null) {
            String pattern = CacheConstants.CACHE_FEEDBACK_KEY + userId + ":*:*";
            Set<String> keys = stringRedisTemplate.keys(pattern);
            if (!keys.isEmpty()) {
                for (String key : keys) {
                    cacheClient.deleteCache(key);
                }
                log.info("Evicted feedback caches for userId: {}, keys: {}", userId, keys);
            }
        }
    }
}